# -*- coding:utf-8 -*- #
from twisted.internet import reactor, defer

import time
from common.utils import json2proxy


class Notifiter(object):
    """send msg to all sockets"""
    _sockets = {}
    _alarm_list = {}
    #_count = 1

    def __init__(self):
        pass

    def register(self, transport):
        self.transport = transport
        if id(self.transport) not in self._sockets:
            self._sockets[id(self.transport)] = transport
            return True
        return False

    @classmethod
    def unregister(self, transport):
        if id(transport) in self._sockets:
            del self._sockets[id(transport)]
            print 'unregister'

    def __del__(self):
        pass
        #self.unregister()

    @classmethod
    def notify(self, msg, level):
        self._alarm_list[msg['item_id']] = msg

        if not level:
            del self._alarm_list[msg['item_id']]

        print 'before Notifiter', type(msg), msg
        self.broadcast(json2proxy([msg]))
        print 'after Notifiter', type(json2proxy([msg])), json2proxy([msg])


    @classmethod
    def broadcast(self, msg):
        #print 'Notifiter', msg

        disconnect = []
        for k in self._sockets.keys():
            transport = self._sockets[k]
            if not transport.connected:
                disconnect.append(k)
            else:
                #transport.write("%s\n" % self._count)
                transport.write(msg)
                #print self._count, 'len sockets', len(self._sockets)
                #self._count += 1

        if disconnect:
            for d in disconnect:
                try:
                    del self._sockets[d]
                except KeyError:
                    pass

    def send_history(self):
        transport = self._sockets[id(self.transport)]
        alarm_list = []
        for i, msg in self._alarm_list.iteritems():
            alarm_list.append(msg)

        #print 'before send_history _alarm_list', type(self._alarm_list), self._alarm_list
        print 'before send_history alarm_list', type(alarm_list), alarm_list
        if alarm_list:
            print 'after send_history alarm_list', type(json2proxy(alarm_list)), json2proxy(alarm_list)
            transport.write(json2proxy(alarm_list))
